import React, {useEffect, useState} from 'react';
import s from './index.less';
import {DotLoading} from "antd-mobile";
import {imgUrls} from "@/pages/Index/ImageUrls";
import {useThrottleFn} from "ahooks";

const Index: React.FC = () => {
  const [isAllImagesLoaded, setIsAllImagesLoaded] = useState<boolean>(false)

  const handleConfirm = ()=>{

  }

  const {
    run
  } = useThrottleFn(handleConfirm, {
    trailing: false,
  });

  // useEffect(() => {
  //   if (!sessionStorage.getItem('token')) {
  //     const intervalId = setInterval(() => {
  //       if (sessionStorage.getItem('token')) {
  //         clearInterval(intervalId);
  //
  //       }
  //     }, 100);
  //     return () => clearInterval(intervalId); // 清除定时器
  //   } else {
  //     // 已经准备好，直接执行你的业务逻辑
  //
  //   }
  // }, [])

  useEffect(() => {
    const preloadImage = async (src: string) => {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = src;
        img.onload = resolve;
        img.onerror = reject;
      });
    };

    const preloadAllImages = async () => {
      if (!imgUrls.length) return setIsAllImagesLoaded(true);
      const promises = imgUrls.map((url: string) => preloadImage(url));
      try {
        await Promise.all(promises);
        setTimeout(() => {
          setIsAllImagesLoaded(true)
        }, 500)
      } catch (err) {
        setIsAllImagesLoaded(true)
      }
    };

    preloadAllImages();
  }, [])

  const handleClick = (): void => {
    console.log(1)
  }

  const {
    run
  } = useThrottleFn(handleClick, {
    trailing: false,
  });


  if (isAllImagesLoaded) {
    return (
      <section className={s.wrap} onClick={run}>
        1
      </section>
    )
  } else {
    return (
      <section className='loading_wrapper'>
        <p>疯狂加载资源中</p>
        <DotLoading/>
      </section>
    )
  }
}

export default Index;
